import Axios, { Method } from 'axios'
import { ref } from 'vue'
import { parse } from 'vue/compiler-sfc'
const axios: any = Axios.create({
  timeout: 30000, // 请求超时时间 30s
})
const baseURL = import.meta.env.MODE === 'development' ? '/dist/data' : './data'
const url = `${baseURL}/main.ts`

interface childrenType {
  link: string
  title: string
  introduction: string
  [p: string]: any
}
interface boxType {
  title: string
  docPath: string
  children: childrenType[]
  [p: string]: any
}
export default function install(): any {
  const fullData = ref<boxType[]>([])
  axios.get(url, { responseType: 'text' }).then((response: any) => {
    const obj = parseCode(response.data)
    const {  boxList=[], editLink = { pattern: '' }  } = obj
    const data = boxList.map((item: any) => {
      const docName = typeof item === 'string' ? item : item.title
      return axios.get(`${baseURL}/${docName}.ts`, { responseType: 'text' })
    })
    Promise.all(data).then((childrenList: any) => {
      const childrenListData = childrenList.map((item: any) => {
        return parseCode(item.data)
      })
      console.log('childrenListData', childrenListData);
      
      fullData.value = boxList.map((item: any, index: number): boxType => {
        if(typeof item === 'string') {
          return {
            title: item,
            docPath: editLink.pattern.replace(':path', `${item}.ts`),
            children: childrenListData[index]
          }
        }
        return {
          ...item,
          docPath: editLink.pattern.replace(':path', `${item}.ts`),
          children: childrenListData[index]
        }
      })
    })
  })
  return {
    fullData
  }
}


function parseCode(codeStr: string): any {
  const code = codeStr.replace(/\/\/# sourceMappingURL=.*$/gm, '');
  // 正则表达式匹配 export default { ... } 或 export default [ ... ]
  const regex = /export\s+default\s*(?:[\{\[](.*)[\}\]]);/s;
  // const regex = /export\s+default\s*\{(.*)\};/s; 
  const match = code.match(regex);

  if (match) {
    try {
      if (match[0][match[0].length - 2] === '}') { // 对象
        const jsonString = "{" + match[1] + "}";
        return JSON.parse(jsonString);
      } else if(match[0][match[0].length - 2] === ']') { // 数组
        // 需要更仔细地处理数组，因为JSON.parse直接解析"[...];"会报错
        const jsonArray = "[" + match[1] + "]"; //去除多余空格
        return JSON.parse(jsonArray);
      }
    } catch (error) {
      console.error("JSON 解析错误:", error);
      return null; // 返回 null 表示解析失败
    }
  } else {
    console.log("没有匹配到对象字面量或数组字面量");
    return null; // 返回 null 表示没有匹配到
  }
}



